package com.jz.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by Administrator on 2015/11/12.
 * 服务端心跳线程
 */
public class HeartBeatClientThread extends Thread{
    public static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatClientThread.class);
    private Socket server;
    private byte[] value = "alive".getBytes();
    private String HEARTBEAT_IP = "127.0.0.1";
    private int HEARTBEAT_PORT = 10101;

    public static void main(String[] args){
        new HeartBeatClientThread().start();
    }

    public HeartBeatClientThread(String ip, int port) {
        super();
        this.HEARTBEAT_IP = ip;
        this.HEARTBEAT_PORT = port;
        init();
    }

    public HeartBeatClientThread() {
        super();
        init();
    }

    private void init(){
        try {
            LOGGER.info("client:start client thread");
            server = new Socket(HEARTBEAT_IP, HEARTBEAT_PORT);
        }catch (Exception e){
            LOGGER.error("客户端心跳线程初始化失败",e);
            handle();
        }
    }

    public void run() {
        while (true) {
            try {
                OutputStream out = server.getOutputStream();
                out.write(value);
                out.flush();
                Thread.sleep(1000);
            } catch (Exception e) {
                LOGGER.error("客户端与服务端心跳线程连接断开,退出程序", e);
                handle();
            }
        }
    }

    /**
     * 客户端与服务端心跳连接断开,退出程序
     * */
    private void handle(){
        LOGGER.info("client:The connection between server and client is lost");
        System.exit(1);
    }
}
